package com.flashcash.solu.app;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Process;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flashcash.solu.BuildConfig;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.BaseActivity;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.squareup.leakcanary.LeakCanary;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.x.leo.apphelper.documented.DocumentMessage;
import com.x.leo.apphelper.log.XLog;

import org.litepal.LitePal;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Locale;

import cn.fraudmetrix.octopus.aspirit.main.OctopusManager;
import io.fabric.sdk.android.Fabric;

import rx.subjects.PublishSubject;
import com.appsflyer.*;
import android.util.Log;
import java.util.Map;
import com.crashlytics.android.Crashlytics;


public class App extends MultiDexApplication {

    // https://stackoverflow.com/questions/11411395/how-to-get-current-foreground-activity-context-in-android/28423385#28423385
    private BaseActivity currentActivity = null;
    public static App instance;

    private static final String AF_DEV_KEY = "hu439bbWdU8r2jvss7R8Cg";

    public void onCreate() {

        super.onCreate();

        Fabric.with(this, new Crashlytics());


        /**  Set Up Conversion Listener to get attribution data **/

        AppsFlyerConversionListener conversionListener = new AppsFlyerConversionListener() {

            /* Returns the attribution data. Note - the same conversion data is returned every time per install */
            @Override
            public void onInstallConversionDataLoaded(Map<String, String> conversionData) {
                for (String attrName : conversionData.keySet()) {
                    Log.d(AppsFlyerLib.LOG_TAG, "attribute: " + attrName + " = " + conversionData.get(attrName));
                }
                //setInstallData(conversionData);
            }

            @Override
            public void onInstallConversionFailure(String errorMessage) {
                Log.d(AppsFlyerLib.LOG_TAG, "error getting conversion data: " + errorMessage);
            }

            /* Called only when a Deep Link is opened */
            @Override
            public void onAppOpenAttribution(Map<String, String> conversionData) {
                for (String attrName : conversionData.keySet()) {
                    Log.d(AppsFlyerLib.LOG_TAG, "attribute: " + attrName + " = " + conversionData.get(attrName));
                }
            }

            @Override
            public void onAttributionFailure(String errorMessage) {
                Log.d(AppsFlyerLib.LOG_TAG, "error onAttributionFailure : " + errorMessage);
            }
        };


        /* This API enables AppsFlyer to detect installations, sessions, and updates. */
        AppsFlyerLib.getInstance().init(AF_DEV_KEY, conversionListener, getApplicationContext());

        instance = this;
        XLog.INSTANCE.initStatus(this);
        new CrashHandler().init(this);

        LitePal.initialize(this);


        XLeoToast.initXLeoToast(this);
        //  Utils.init(this);


        //AdviceBinder.bindAdvice(PointCutEnum.CHATTING_FRAGMENT_UI_POINTCUT, ChattingCustomAdvice.class);
        // AdviceBinder.bindAdvice(PointCutEnum.CHATTING_FRAGMENT_OPERATION_POINTCUT, ChattingPageOperation.class);
        //泄漏检测
        LeakCanary.install(this);

        //ali push
        // initCloudChannel(this);

        DocumentMessage.Companion.initDocumentMessage(this);
        // restrictLanguage(BuildConfig.LANG);


        if (BuildConfig.DEBUG) {
            Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    XLog.INSTANCE.e("uncatch throwable:",e,100);
                    Process.killProcess(Process.myPid());
                    System.exit(0);
                }
            });
            ARouter.openDebug();
        }
        ARouter.openLog();
        ARouter.init(this);
        initTD();
        FirebaseAnalyticsUtils.INSTANCE.initialize(this); // 初始化FirebaseAnalytics
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // restrictLanguage(BuildConfig.LANG);
    }

    public PublishSubject<Boolean> channelOK  = PublishSubject.create();

    public BaseActivity getCurrentActivity() {
        return currentActivity;
    }

    public void setCurrentActivity(BaseActivity currentActivity) {
        this.currentActivity = currentActivity;
    }
    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    private void restrictLanguage(String language) {
        try {
            /*Locale locale = new Locale(language);
            Locale.setDefault(locale);*/
            Configuration configuration = getResources().getConfiguration();
            DisplayMetrics metrics = getResources().getDisplayMetrics();
            if ("zh".equals(language)) {
                configuration.locale = Locale.SIMPLIFIED_CHINESE;
            } else if ("en".equals(language)) {
                configuration.locale = Locale.ENGLISH;
            } else if ("in".equals(language)) {
                configuration.locale = new Locale("in", "ID", "");
            } else if ("vi".equals(language)) {
                configuration.locale = new Locale("vi", "VN", "");
            }
            /*Locale.setDefault(configuration.locale);*/
            getResources().updateConfiguration(configuration, metrics);
        } catch (Throwable e) {
            XLog.INSTANCE.e("", e, 100);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    /**
     * 初始化云推送通道
     *
     * @param applicationContext
     */
//    private void initCloudChannel(Context applicationContext) {
//        PushServiceFactory.init(applicationContext);
//        CloudPushService pushService = PushServiceFactory.getCloudPushService();
//        pushService.register(applicationContext, new CommonCallback() {
//            @Override
//            public void onSuccess(String response) {
//                XLog.INSTANCE.i( "init cloudchannel success",10);
//                CustomPushNotifactionManager.init();
//
//                channelOK.onNext(true);
//            }
//
//            @Override
//            public void onFailed(String errorCode, String errorMessage) {
//                XLog.INSTANCE.d("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage,10);
//            }
//        });

//        // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
//        MiPushRegister.register(applicationContext, BuildConfig.ALIPUSH_MI_APPID, BuildConfig.ALIPUSH_MI_APPKEY);
//        // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
//        HuaWeiRegister.register(applicationContext);
//    }

    /**
     * init 同盾
     */
    private static void initTD() {
        if (!TextUtils.isEmpty(BuildConfig.TONGDUN_PARENT_CODE) && !TextUtils.isEmpty(BuildConfig.TONGDUN_PARENT_KEY)) {
            OctopusManager.getInstance().init(App.instance.getBaseContext(), BuildConfig.TONGDUN_PARENT_CODE, BuildConfig.TONGDUN_PARENT_KEY);
            OctopusManager.getInstance().setPrimaryColorResId(R.color.theme_purple);
            OctopusManager.getInstance().setTitleColorResId(R.color.white);
            OctopusManager.getInstance().setShowWarnDialog(true);
        }
    }

}